package com.xiaoyaoji.txt.util;

import com.google.common.collect.Lists;
import com.xiaoyaoji.txt.pojo.dto.TxtDTO;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TxtAnalysisUtils {

    public static List<TxtDTO> exec(InputStream inputStream) throws Exception {
        //转换流
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("utf8"));
        //高效缓冲流
        BufferedReader reader = new BufferedReader(inputStreamReader);
        //存储每个请求
        List<TxtDTO> txtDTOList = Lists.newArrayList();

        //解析txt
        List<String> lineList = Lists.newArrayList();
        String line;
        while ((line = reader.readLine()) != null) {
            // 跳过空白行
            if(StringUtils.isBlank(line)) continue;
            // 把右边的空格删掉
            line = line.replaceAll("\\s*$", "");
            // “    ”转“tab”
            line = line.replaceAll("    ", "\t");
            // 删除第一个“tab”
            if (line.charAt(0) == '\t') {
                line = line.substring(1);
            }
            // 标题
            if (Character.isDigit(line.charAt(0))) {
                addTxtDTO(lineList, txtDTOList);
                // 清除
                lineList.clear();
            }
            lineList.add(line);
        }

        //读取最后一个
        addTxtDTO(lineList, txtDTOList);
        return txtDTOList;
    }

    /**
     * String转TxtBean
     *
     * @param line
     * @return TxtBean
     */
    private static TxtDTO toTxtBean(String[] line) throws IOException {
        if (line.length < 2) return null;
        TxtDTO bean = new TxtDTO();
        //标题
        bean.setTitle(line[0].trim());
        //请求方式、地址
        String[] urlAndMethodTemp = line[1].trim().split(" ");
        if (urlAndMethodTemp.length < 2) return null;
        bean.setRequestMethod(urlAndMethodTemp[0].trim());
        bean.setUrl(urlAndMethodTemp[1].trim());


        boolean isRequestTemp = true;
        String requestContent = "";
        String responseContent = "";
        for (int i = 2; i < line.length; i++) {
            if ("request:".equalsIgnoreCase(line[i])) {
                isRequestTemp = true;
                continue;
            }
            if ("response:".equalsIgnoreCase(line[i])) {
                isRequestTemp = false;
                continue;
            }
            if (isRequestTemp) {
                requestContent += line[i].substring(1) + "\n";
            } else {
                responseContent += line[i].substring(1) + "\n";
            }
        }

        TxtDTO.Property request = new TxtDTO.Property();
        TxtDTO.Property response = new TxtDTO.Property();
        ergodic(request, requestContent);
        ergodic(response, responseContent);
        bean.setRequest(request);
        bean.setResponse(response);

        return bean;
    }


    private static void ergodic(TxtDTO.Property property, String content) throws IOException {
        if ("".equals(content) || property == null) return;

        //输入流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes(Charset.forName("utf8")));
        //转换流
        InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, Charset.forName("utf8"));
        //高效缓冲流
        BufferedReader reader = new BufferedReader(inputStreamReader);

        TxtDTO.Property p = null;
        ArrayList<TxtDTO.Property> properties = new ArrayList<>();
        String contentTemp = "";

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.charAt(0) != '\t') {
                p = new TxtDTO.Property();
                int index = line.indexOf(":");
                if (index == -1 || index == line.length()) {
                    p.setName(line.trim());
                } else {
                    p.setName(line.substring(0, index).trim());
                    String typeTemp = line.substring(index + 1).trim();
                    int i = typeTemp.indexOf(" ");
                    if (i == -1 || i == typeTemp.length()) {
                        p.setType(typeTemp.trim());
                    } else {
                        p.setType(typeTemp.substring(0, i).trim());
                        p.setDescription(typeTemp.substring(i + 1).trim());
                    }
                    if ("{".equals(p.getType())) {
                        p.setType("object");
                    }
                }
                ergodic(p, contentTemp);
                contentTemp = "";
                properties.add(p);
            } else {
                contentTemp += line.substring(1) + "\n";
            }
        }
        ergodic(p, contentTemp);
        property.setChildrenProperties(properties);
    }

    private static void addTxtDTO(List<String> lineList, List<TxtDTO> txtDTOList) throws IOException {
        String[] temp = new String[lineList.size()];
        lineList.toArray(temp);
        TxtDTO txtTemp = toTxtBean(temp);
        if (Objects.nonNull(txtTemp)) {
            txtDTOList.add(txtTemp);
        }
    }

}
